package com.example.jobtask.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.example.jobtask.util.DynamicClassLoader;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 文件管理控制器
 */
@RestController
@RequestMapping("/api/files")
@CrossOrigin(origins = "*")
public class FileController {
    
    @Autowired
    private DynamicClassLoader dynamicClassLoader;
    
    /**
     * 创建或更新Java文件
     */
    @PostMapping("/save")
    public ResponseEntity<?> saveJavaFile(@RequestBody SaveFileRequest request) {
        try {
            String filePath = request.getFilePath();
            String content = request.getContent();
            
            // 验证文件路径
            if (!filePath.endsWith(".java")) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error("文件必须是Java文件"));
            }
            
            // 创建目录结构
            Path path = Paths.get(filePath);
            Files.createDirectories(path.getParent());
            
            // 保存文件
            Files.write(path, content.getBytes("UTF-8"));
            
            return ResponseEntity.ok(ApiResponse.success("文件保存成功", filePath));
            
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("保存文件失败: " + e.getMessage()));
        }
    }
    
    /**
     * 读取Java文件内容
     */
    @GetMapping("/read")
    public ResponseEntity<?> readJavaFile(@RequestParam String filePath) {
        try {
            Path path = Paths.get(filePath);
            
            if (!Files.exists(path)) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(ApiResponse.error("文件不存在"));
            }
            
            String content = Files.readString(path);
            
            Map<String, Object> data = new HashMap<>();
            data.put("filePath", filePath);
            data.put("content", content);
            
            return ResponseEntity.ok(ApiResponse.success("读取文件成功", data));
            
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("读取文件失败: " + e.getMessage()));
        }
    }
    
    /**
     * 删除Java文件
     */
    @DeleteMapping("/delete")
    public ResponseEntity<?> deleteJavaFile(@RequestParam String filePath) {
        try {
            Path path = Paths.get(filePath);
            
            if (!Files.exists(path)) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(ApiResponse.error("文件不存在"));
            }
            
            Files.delete(path);
            
            return ResponseEntity.ok(ApiResponse.success("文件删除成功"));
            
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("删除文件失败: " + e.getMessage()));
        }
    }
    
    /**
     * 列出热插拔目录中的Java文件
     */
    @GetMapping("/list")
    public ResponseEntity<?> listJavaFiles() {
        try {
            String hotplugDir = dynamicClassLoader.getHotplugDir();
            Path dirPath = Paths.get(hotplugDir);
            
            if (!Files.exists(dirPath)) {
                Files.createDirectories(dirPath);
            }
            
            List<Map<String, Object>> fileList = Files.walk(dirPath)
                    .filter(path -> path.toString().endsWith(".java"))
                    .map(path -> {
                        Map<String, Object> fileInfo = new HashMap<>();
                        fileInfo.put("path", path.toString());
                        fileInfo.put("name", path.getFileName().toString());
                        fileInfo.put("relativePath", dirPath.relativize(path).toString());
                        try {
                            fileInfo.put("size", Files.size(path));
                            fileInfo.put("lastModified", Files.getLastModifiedTime(path).toMillis());
                        } catch (IOException e) {
                            // 忽略获取文件信息失败的情况
                        }
                        return fileInfo;
                    })
                    .collect(Collectors.toList());
            
            return ResponseEntity.ok(ApiResponse.success("获取文件列表成功", fileList));
            
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("获取文件列表失败: " + e.getMessage()));
        }
    }
    
    /**
     * 编译Java文件
     */
    @PostMapping("/compile")
    public ResponseEntity<?> compileJavaFile(@RequestParam String filePath) {
        try {
            boolean success = dynamicClassLoader.compileJavaFile(filePath);
            
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("编译成功"));
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(ApiResponse.error("编译失败，请检查代码语法"));
            }
            
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("编译失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取热插拔目录路径
     */
    @GetMapping("/hotplug-dir")
    public ResponseEntity<?> getHotplugDir() {
        String hotplugDir = dynamicClassLoader.getHotplugDir();
        return ResponseEntity.ok(ApiResponse.success("获取热插拔目录成功", hotplugDir));
    }
    
    /**
     * 生成建议的文件路径
     */
    @PostMapping("/suggest-path")
    public ResponseEntity<?> suggestFilePath(@RequestBody SuggestPathRequest request) {
        try {
            String className = request.getClassName();
            String packageName = request.getPackageName();
            
            if (className == null || className.trim().isEmpty()) {
                return ResponseEntity.badRequest()
                        .body(ApiResponse.error("类名不能为空"));
            }
            
            // 默认包名
            if (packageName == null || packageName.trim().isEmpty()) {
                packageName = "com.example.tasks";
            }
            
            // 生成文件路径
            String hotplugDir = dynamicClassLoader.getHotplugDir();
            String packagePath = packageName.replace(".", File.separator);
            String filePath = Paths.get(hotplugDir, packagePath, className + ".java").toString();
            
            Map<String, Object> result = new HashMap<>();
            result.put("filePath", filePath);
            result.put("className", packageName + "." + className);
            result.put("packageName", packageName);
            
            return ResponseEntity.ok(ApiResponse.success("生成路径成功", result));
            
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.error("生成路径失败: " + e.getMessage()));
        }
    }
    
    /**
     * 保存文件请求
     */
    public static class SaveFileRequest {
        private String filePath;
        private String content;
        
        public String getFilePath() { return filePath; }
        public void setFilePath(String filePath) { this.filePath = filePath; }
        
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
    }
    
    /**
     * 建议路径请求
     */
    public static class SuggestPathRequest {
        private String className;
        private String packageName;
        
        public String getClassName() { return className; }
        public void setClassName(String className) { this.className = className; }
        
        public String getPackageName() { return packageName; }
        public void setPackageName(String packageName) { this.packageName = packageName; }
    }
    
    /**
     * API响应封装类
     */
    public static class ApiResponse {
        private boolean success;
        private String message;
        private Object data;
        private long timestamp;
        
        public ApiResponse(boolean success, String message, Object data) {
            this.success = success;
            this.message = message;
            this.data = data;
            this.timestamp = System.currentTimeMillis();
        }
        
        public static ApiResponse success(String message) {
            return new ApiResponse(true, message, null);
        }
        
        public static ApiResponse success(String message, Object data) {
            return new ApiResponse(true, message, data);
        }
        
        public static ApiResponse error(String message) {
            return new ApiResponse(false, message, null);
        }
        
        public boolean isSuccess() { return success; }
        public String getMessage() { return message; }
        public Object getData() { return data; }
        public long getTimestamp() { return timestamp; }
    }
}